import axios from "axios";
import store from "@/store"
//引入进度条
import nprogress from 'nprogress';
//start：进度条开始 done：进度条结束
import "nprogress/nprogress.css"
import router from "@/router";

let requests= axios.create({
  baseURL: "http://localhost:8081/api",
  timeout: 200000
});


//请求拦截器
requests.interceptors.request.use((config) => {
  nprogress.start();
  //不属于注册登录
  if (config.url === "/login" || config.url === "/register"){
    return config;
  }else {
    //存在token
    if (store.state.user.token){
      config.headers.token = store.state.user.token
      return config;
    }else {
      //不存在token
      router.replace({
        path:'/login'
      })
      alert("未登录，请登录后访问")
      location.reload()
    }
  }
})

//响应拦截器
requests.interceptors.response.use((res)=>{
  //进度条结束
  nprogress.done();
  //成功回调函数
  return res.data;
},(res)=>{
  //失败回调函数
  return Promise.reject("服务器响应数据失败")
})

export default requests;
